package com.ucar.train.service.zhoujinmu.pattern;



import com.ucar.train.service.zhoujinmu.exception.Exception1;

import java.util.concurrent.*;

/**
 * @author zhoujinmu
 * @title RepairEngin
 * @projectName desiginpattern
 * @description TODO
 * @created 2019-08-21 16:51
 **/
public class EngineRepair extends Handler {

    private static int time = 0;
    private int level;

    public EngineRepair(int level) {
        super(level);
        this.level = level;
    }

    @Override
    protected void repair(final Car car) throws Exception {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        FutureTask<String> future = new FutureTask<>(new Callable<String>() {
            String message = "";

            @Override
            public String call() throws Exception {
                System.out.println("------------进入发动机保养流程----------------");
                Thread.sleep(1000);
                int random = (int) (1 + Math.random() * 10);
                if (random > 5) {
                    message = "保养发动机成功";
                    car.setRepairState(car.getRepairState() + 1);
                } else {
                    message = "保养发动机失败，自调用";
                }
                return message;
            }
        }
        );
        executorService.execute(future);

        try {
            String result = future.get(4, TimeUnit.SECONDS);
            System.out.println(result);
        } catch (TimeoutException | InterruptedException | ExecutionException e) {
            car.setRepairState(level);
            time++;
            System.out.println("保养发动机超时了!" + time + "次");
            if (time >= 3) {
                System.out.println("保养发动机超时3次退出");
                future.cancel(true);
                executorService.shutdownNow();
                throw new Exception1();
            }
        }
        System.out.println("--------------退出发动机保养流程----------------");
    }

}
